package com.example.environmentset.service.impl;

import com.example.environmentset.service.PortSetService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @author fangyuan.xia
 * @since 2022-08-15
 */
@Slf4j
public class PropertiesPortSetImpl implements PortSetService {
    @SneakyThrows
    @Override
    public boolean set(String context, int port) {
        Path portFilePath = getPath();
        if (!Files.exists(portFilePath)) {
            Files.createFile(portFilePath);
        }
        Properties properties = new Properties();
        properties.load(Files.newInputStream(portFilePath));
        properties.setProperty(context, port + "");
        properties.store(Files.newOutputStream(portFilePath), new Date().toString());
        return true;
    }

    @SneakyThrows
    @Override
    public Map<String, Integer> get() {
        Path portFilePath = getPath();
        if (!Files.exists(portFilePath)) {
            return Collections.emptyMap();
        }
        Properties properties = new Properties();
        properties.load(Files.newInputStream(portFilePath));
        Set<Map.Entry<Object, Object>> entries = properties.entrySet();
        Map<String, Integer> result = new HashMap<>(entries.size());
        for (Map.Entry<Object, Object> contextAndPort : entries) {
            result.put(contextAndPort.getKey().toString(), Integer.parseInt(contextAndPort.getValue().toString()));
        }
        return result;
    }

    public static Path getPath() {
        // 读写这个文件 ${user.home}/.port/port.properties
        return Paths.get(System.getProperty("user.home"), ".port", "port.properties");
    }
}
